<?php

namespace App\Sidong\Controllers;

use App\Handlers\ImageUploadHandler;
use App\Models\Tenant;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Http\Request;

class TenantController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '商户管理';


    public function index(Content $content)
    {
        return $content
            ->title($this->title())
            ->breadcrumb(['text' => '商户列表'])
            ->body($this->grid());
    }

    public function edit($id, Content $content)
    {
        return $content
            ->title('编辑商户')
            ->breadcrumb(['text' => '商户列表', 'url' => 'tenants'], ['text' => '编辑商户'])
            ->body($this->form()->edit($id));
    }

    protected function grid()
    {
        $grid = new Grid(new Tenant);
        $grid->disableExport();
        $grid->disableFilter();
        $grid->disableColumnSelector();
        $grid->disableBatchActions();
        $grid->disablePagination();
        $grid->actions(function ($actions) {
            $actions->disableDelete();
            $actions->disableView();
        });

        $admin = \Admin::user();
        $tenant = Tenant::where([
            'admin_prefix' => config('admin.route.prefix'),
            'admin_id' => $admin->id,
        ])->first();
        if ($tenant) {
            $grid->disableCreateButton();
        }
        $grid->model()->where(['admin_id' => $admin->id, 'admin_prefix' => config('admin.route.prefix')]);
//        if ($grid->model()->get()->isEmpty()) {
//            admin_error('还没创建商户');
//        }

        $grid->column('short_name', '简称')->display(function($short_name) {
            return '<img width="35" src="' . $this->logo_url . '"/>' . $short_name;
        });
        $grid->column('phone', '手机号码');
        $grid->column('app_id', '公众号APPID')->copyable();
        $grid->column('mch_id', '微信商户ID')->copyable();
        $grid->column('mch_key', '微信商户KEY')->copyable();
        $grid->column('weapp_id', '小程序APPID')->copyable();
        $grid->column('contact_number', '联系电话');
        $grid->column('area', '省市区')->display(function() {
            $province = \DB::table('china_area')->where(['code' => $this->province_id])->first();
            $city = \DB::table('china_area')->where(['code' => $this->city_id])->first();
            $district = \DB::table('china_area')->where(['code' => $this->district_id])->first();
            return $province->name . '/' . $city->name . '/' . $district->name;
        });
        $grid->column('address', '详细地址');
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed   $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Tenant::findOrFail($id));
        $show->title = '详情';
        $show->field('name', '名称');
        $show->field('short_name', '简称');
        $show->field('logo_url', 'LOGO')->image();
        $show->field('phone', '手机');
        $show->field('app_id', '公众号APPID');
        $show->field('mch_id', '微信商户ID');
        $show->field('mch_key', '微信商户KEY');
        $show->field('weapp_id', '小程序APPID');
        $show->field('weapp_secret', '小程序secret');
        $show->field('contact_number', '联系电话');
        $show->field('address', '详细地址');
        $show->field('longitude', '经度');
        $show->field('latitude', '纬度');

        return $show;
    }

    public function create(Content $content)
    {
        return $content
            ->title('完善商户信息')
            ->body($this->form());
    }

    public function store()
    {
        $data = \request()->all();
        if ($message = $this->form()->validationMessages($data)) {
            return back()->withInput()->withErrors($message);
        }
        $prefix = config('admin.route.prefix');
        if (!column_exists("{$prefix}_users", ['tenant_id'])) {
            add_column_to_table("{$prefix}_users", 'tenant_id', 'integer', 10, '管理员ID', 'id');
        }
        $admin = \Admin::user();
        $uploader = new ImageUploadHandler();

        $tenant = Tenant::create([
            'admin_id' => $admin->id,
            'admin_prefix' => $prefix,
            'phone' => str_replace(' ', '', $data['phone']),
            'app_id' => $data['app_id'],
            'mch_id' => $data['mch_id'],
            'mch_key' => $data['mch_key'],
//            'cert_path' => $data['cert_path'],
//            'key_path' => $data['key_path'],
            'weapp_id' => $data['weapp_id'],
            'md5_weapp_id' => $data['md5_weapp_id'],
            'weapp_secret' => $data['weapp_secret'],
            'name' => $data['name'],
            'short_name' => $data['short_name'],
            'contact_number' => str_replace(' ', '', $data['contact_number']),
            'province_id' => $data['province_id'],
            'city_id' => $data['city_id'],
            'district_id' => $data['district_id'],
            'address' => $data['address'],
            'longitude' => $data['longitude'],
            'latitude' => $data['latitude'],
        ]);
        if ($data['logo_url']) {
            $folder_name =  'uploads/' . $data['admin_prefix'] . '/tenant_logo/' . date("Ym/d", time());
            $result = $uploader->save($data['logo_url'], $folder_name, $admin->id);
            $tenant->logo_path = $result['original_path'];
            $tenant->logo_url = $result['path'];
            $tenant->save();
        }
        if ($data['cert_path']) {
            $folder_name =  '/uploads/' . $data['admin_prefix'] . '/tenant_cert/' . date("Ym/d", time());
            $extension = strtolower($data['cert_path']->getClientOriginalExtension()) ?: 'pem';
            $filename = 'apiclient_cert.' . $extension;
            $data['cert_path']->move(public_path() . '/' . $folder_name, $filename);
            $tenant->cert_path = $folder_name . "/{$filename}";
            $tenant->save();
        }
        if ($data['key_path']) {
            $folder_name =  '/uploads/' . $data['admin_prefix'] . '/tenant_cert/' . date("Ym/d", time());
            $extension = strtolower($data['key_path']->getClientOriginalExtension()) ?: 'pem';
            $filename = 'apiclient_key.' . $extension;
            $data['key_path']->move(public_path() . '/' . $folder_name, $filename);
            $tenant->key_path = $folder_name . "/{$filename}";
            $tenant->save();
        }
        $admin->tenant_id = $tenant->id;
        admin_toastr('操作成功');
        $admin->save();
//        return redirect(admin_url('/'));
        return redirect()->back();
    }

    protected function form()
    {
        $form = new Form(new Tenant);
        $form->setTitle('商户信息(请填写完整否则将无法正常使用)');
        $form->disableReset();
        $form->disableCreatingCheck();
        $form->disableEditingCheck();
        $form->disableViewCheck();
        $form->tools(function (Form\Tools $tools) {
            $tools->disableList();
        });
        $uri = \request()->getRequestUri();
        $uri_arr = array_filter(explode('/', $uri));
        $form->hidden('admin_prefix')->default(reset($uri_arr));
        $form->column(1/2, function($form) {
            $form->mobile('phone', '手机号码')
                ->options(['mask' => '999 9999 9999'])
                ->placeholder('请输入手机号码')
                ->rules('required|phone:CN,mobile')
                ->width(100);
            $form->text('name', '名称')
                ->placeholder('请输入商户名称')
                ->rules('required');
            $form->text('short_name', '简称')
                ->placeholder('请输入商户简称')
                ->help('商户简称将作为小程序的商户名称，建议2-4个汉字')
                ->rules('required');
            $form->image('logo_url', 'LOGO')
                ->placeholder('请上传商户LOGO')
                ->move('logo/' . date('Ym', now()->timestamp))
                ->help('图片格式只支持 jpg、jpeg、png，大小不要超过2M，尺寸建议128*128')
                ->rules('required', [
                    'required' => '请上传LOGO'
                ])->uniqueName();
            $form->mobile('contact_number', '联系电话')
                ->options(['mask' => '9999 9999 9999'])
                ->placeholder('请输入联系电话')
                ->width(100)
                ->rules('required');
            $form->distpicker([
                'province_id' => '省份',
                'city_id' => '市',
                'district_id' => '区',
            ], '省市区')->default([
                'province' => 440000, // 440000
                'city'     => 440100, // 440100
                'district' => 440104, // 440104
            ])
                ->rules('required');
            $form->text('address', '详细地址')
                ->placeholder('请输入详细地址')
                ->rules('required');
            $form->latlong('latitude', 'longitude', '经纬度坐标')
                ->rules('required');
        });
        $form->column(1/2, function($form) {
            $form->text('app_id', '公众号ID')
                ->placeholder('请输入公众号ID')
                ->help('请登录微信公众平台在公众号信息中查看公众号ID')
                ->rules('required');
            $form->text('mch_id', '微信商户ID')
                ->placeholder('请输入微信商户ID')
                ->help('请登录微信商户平台在商户信息中查看商户ID，也可以通过申请时的邮件查看')
                ->rules('required');
            $form->text('mch_key', '微信商户KEY')
                ->placeholder('请输入微信商户KEY')
                ->help('请登录微信商户平台在商户信息中查看商户KEY，也可以通过申请时的邮件查看')
                ->rules('required');
            $form->text('weapp_id', '小程序ID')
                ->placeholder('请输入小程序ID')
                ->help('请登录微信公众平台在小程序信息中查看小程序ID，注意区分这里的不是公众号ID')
                ->rules('required');
            $form->text('weapp_secret', '小程序秘钥')
                ->placeholder('请输入小程序秘钥')
                ->help('请登录微信公众平台在小程序信息中查看小程序秘钥，注意区分这里的不是公众号秘钥。如果没有设置小程序秘钥，请先登录微信公众平台进行设置')
                ->rules('required');
            $form->file('cert_path', '证书PEM')
                ->placeholder('请上传微信商户证书PEM文件')
                ->help('请登录微信商户平台下载证书，选择其中的 apiclient_cert.pem 文件上传，此文件用于微信支付')
//                ->rules('required|mimes:pem');
//                ->move('cert/' . date('Ym', now()->timestamp))
                ->rules('required');
            $form->file('key_path', '证书KEY')
                ->placeholder('请上传微信商户证书KEY文件')
                ->help('请登录微信商户平台下载证书，选择其中的 apiclient_key.pem 文件上传，此文件用于微信支付')
//                ->rules('required|mimes:pem');
//                ->move('cert/' . date('Ym', now()->timestamp))
                ->rules('required');
        });
        $form->saving(function($form) {
            $form->phone = str_replace(' ', '', $form->phone);
            $form->contact_number = str_replace(' ', '', $form->contact_number);
            $form->md5_weapp_id = md5($form->weapp_id);
        });
        return $form;
    }
}
